package tp.badugi.server;

import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;

public class Deck {

	private List<Card> drawPile;
	private List<Card> discardPile;
	private List<Card> cardsInPlay;
	
	public Deck() {
		drawPile = new ArrayList<Card>(EnumSet.allOf(Card.class));
		discardPile = new ArrayList<Card>();
		cardsInPlay = new ArrayList<Card>();
		Collections.shuffle(drawPile);
	}
	
	public Card drawCard() {
		if (drawPile.isEmpty()) {
			shuffleAndReuseDiscardPile();
		}
		Card card = drawPile.remove(0);
		cardsInPlay.add(card);
		return card;
	}
	
	public Card exchangeCard(Card card) {
		// If the card was not in play before throw exception
		if (!cardsInPlay.remove(card)) {
			throw new IllegalArgumentException();
		}
		discardPile.add(card);
		return drawCard();
	}
	
	public void shuffle() {
		drawPile = new ArrayList<Card>(EnumSet.allOf(Card.class));
		Collections.shuffle(drawPile);
		discardPile.clear();
	}
	
	private void shuffleAndReuseDiscardPile() {
		Collections.shuffle(discardPile);
		drawPile = discardPile;
		discardPile = new ArrayList<Card>();
	}

}
